class_name World
extends Node2D

@export var bgm = AudioStream

@onready var genometry: TileMapLayer = $TileMap/Genometry
@onready var camera_2d: Camera2D = $Player/Camera2D
@onready var player: Player = $Player

func _ready() -> void:
	# 设置窗口大小
	get_window().size = Vector2i(200, 100)
	# 获取屏幕尺寸
	var screen_size = DisplayServer.screen_get_size()
	# 计算右下角位置
	var window_size = get_window().size
	var x = screen_size.x - window_size.x
	var y = screen_size.y - window_size.y
	# 设置窗口位置
	get_window().position = Vector2i(x, y)

	var used := genometry.get_used_rect().grow(-1)
	var tile_size := genometry.tile_set.tile_size
	
	# 根据地图动态设置相机边界
	camera_2d.limit_top = genometry.position.y + used.position.y * tile_size.y
	camera_2d.limit_bottom = genometry.position.y + used.end.y * tile_size.y
	camera_2d.limit_right = genometry.position.x + used.end.x * tile_size.x
	camera_2d.limit_left = genometry.position.x + used.position.x * tile_size.x
	# 取消过渡动画
	camera_2d.reset_smoothing()
	camera_2d.force_update_scroll()
	
	if bgm:
		SoundManager.play_bgm(bgm)

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_cancel"):
		Game.back_to_title()
	
func update_player(pos: Vector2, direction: Player.Direction) -> void:
	player.global_position = pos
	player.direction = direction
	camera_2d.reset_smoothing()
	camera_2d.force_update_scroll()

func to_dict() -> Dictionary:
	var enemies_alive := []
	# 节点名称转相对路径
	for node in get_tree().get_nodes_in_group("enemies"):
		var path := get_path_to(node) as String
		enemies_alive.append(path)
	return {
		enemies_alive = enemies_alive
	}

func from_dict(world_stats: Dictionary) -> void:
	for node in get_tree().get_nodes_in_group("enemies"):
		var path := get_path_to(node) as String
		if path not in world_stats.enemies_alive:
			node.queue_free()
	
